package com.app.asktom.component;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public class HttpMultipartHelper {
	private ArrayList<NameValuePair> formDatas = new ArrayList<NameValuePair>();
	private String uploadUrl;
	private String sourceFileDir;
	private static final String lineEnd = "\r\n";
	private static final String twoHyphens = "--";
	private String boundary = String.valueOf(System.currentTimeMillis());
	private HttpURLConnection conn = null;
	private DataOutputStream dos = null;
	private File sourceFile = null;
	private String response;
	
	public void addToMap(String key, String value){
		this.formDatas.add(new BasicNameValuePair(key, value));
	}
	
	public void setSourceFileDir(String sourceFileDir) {
		this.sourceFileDir = sourceFileDir;
	}
	
	public void setUploadUrl(String uploadUrl) {
		this.uploadUrl = uploadUrl;
	}
	
	public void sendRequest(){
		this.sourceFile = new File(this.sourceFileDir);
		int serverResponseCode = 0;
		
		if(this.sourceFile.isFile()){
			int bytesRead, bytesAvailable, bufferSize;
		    byte[] buffer;
		    int maxBufferSize = 1 * 1024 * 1024; 
		    
			try {
				FileInputStream fis = new FileInputStream(this.sourceFile);
				URL url = new URL(this.uploadUrl);
				
				this.conn = (HttpURLConnection) url.openConnection();
				this.conn.setDoInput(true); // Allow Inputs
				this.conn.setDoOutput(true); // Allow Outputs
				this.conn.setUseCaches(false); // Don't use a Cached Copy
				this.conn.setRequestMethod("POST");
				this.conn.setRequestProperty("Connection", "Keep-Alive");
				this.conn.setRequestProperty("ENCTYPE", "multipart/form-data");
				this.conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + this.boundary);
				this.conn.setRequestProperty("file", this.sourceFileDir);
				
				this.dos = new DataOutputStream(conn.getOutputStream());
				
				dos.writeBytes(twoHyphens + this.boundary + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+this.sourceFileDir+"\""+ lineEnd);
				dos.writeBytes("Content-Type: image/jpg"+lineEnd);
				dos.writeBytes("Content-Transfer-Encoding: binary"+lineEnd);
				dos.writeBytes(lineEnd);
				
				// create a buffer of  maximum size
				bytesAvailable = fis.available();
				
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];
				
				// read file and write it into form...
				bytesRead = fis.read(buffer, 0, bufferSize);
				
				while(bytesRead > 0){
					dos.write(buffer, 0 ,bufferSize);
					bytesAvailable = fis.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fis.read(buffer, 0, bufferSize);
				}
				
				dos.writeBytes(lineEnd);
	            
	            if(!this.formDatas.isEmpty()){
	            	for(NameValuePair formData:formDatas){
	            		dos.writeBytes(twoHyphens + this.boundary + lineEnd);
	                    dos.writeBytes("Content-Disposition: form-data; name=\""+formData.getName()+"\"" + lineEnd);
	                    dos.writeBytes(lineEnd);
	                    dos.writeBytes(formData.getValue()+lineEnd);
	                    Log.i("UPSTAT", formData.getName()+" "+formData.getValue());
	            	}
	            }
	            
	            dos.writeBytes(twoHyphens + this.boundary + twoHyphens + lineEnd);
	            
	            serverResponseCode = conn.getResponseCode();
	            String serverResponseMsg = conn.getResponseMessage();
	            
	            this.response = this.convertStreamToString(conn.getInputStream());
	            
	            Log.i("UPSTAT", "HTTP RESP is " +serverResponseCode +" "+serverResponseMsg+" "+this.response);
	            
	            fis.close();
	            dos.flush();
	            dos.close();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				this.response = e.getMessage();
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				this.response = e.getMessage();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				this.response = e.getMessage();
			}
			
		}
		
	}
	
	public String getResponse() {
		return this.response;
	}
	
	private String convertStreamToString(InputStream is) {

	    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
	    StringBuilder sb = new StringBuilder();

	    String line = null;
	    try {
	        while ((line = reader.readLine()) != null) {
	            sb.append((line + "\n"));
	        }
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	    return sb.toString();
	}
	
}
